<template>
  <div class="">
    <a-row type="flex" justify="center">
      <a-button :type="typeIndex === 0 ? 'primary' : 'default'" @click="splitScreen(0)">单屏</a-button>
      <a-button :type="typeIndex === 1 ? 'primary' : 'default'" @click="splitScreen(1)">四分屏</a-button>
      <a-button :type="typeIndex === 2 ? 'primary' : 'default'" @click="splitScreen(2)">九分屏</a-button>
      <a-button :type="typeIndex === 3 ? 'primary' : 'default'" @click="splitScreen(3)">十六分屏</a-button>
      <a-button @click="showVideoModal">轮播</a-button>
      <a-button @click="toggleFullScreen">
        <FullscreenOutlined />
      </a-button>
      <!-- <a-button ><ArrowLeftOutlined /></a-button> -->
    </a-row>
    <a-row>
      <a-col :span="6">
        <a-input-search v-model:value="searchValue" style="margin-bottom: 8px;width:310px" placeholder="搜索" />
        <a-button @click="synchronousTree">同步数据</a-button>
        <div style="max-height: 700px;overflow-y: auto;">
          <a-tree :tree-data="treeData" :auto-expand-parent="autoExpandParent" v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys" @select="treeSelect"
            :replaceFields="{ children: 'children', title: 'name', key: 'name' }">
          </a-tree>
        </div>

      </a-col>
      <a-col :span="18" id="videId">
        <a-row>
          <a-col v-for="(item, index) in playerList" :span="span[typeIndex]"
            :class="{ active: livePlayerIndex == index }" style="padding: 1px;" @click="LivePlayerClick(index)">
            <LivePlayer :videoUrl="item.url" fluent :controls="false" autoplay live stretch alt="无信号">
            </LivePlayer>
            <a-button v-if="!item.url" @click="showVideoListModal(index)"
              style="position: absolute;z-index: 999;right: 10px;top: 10px;">选择通道</a-button>
            <a-button v-if="item.url" @click="item.url = ''"
              style="position: absolute;z-index: 999;right: 10px;top: 10px;">关闭</a-button>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <videoModal ref="videoModalRef" @change="videoChange" />
    <videoListModal ref="videoListModalRef" @rowClick="videoSrcChange" />
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import LivePlayer from '@liveqing/liveplayer-v3'
import videoModal from './components/index.vue'
import videoListModal from './components/videoList.vue';
import { serverUrlApi } from '/@/api/videoMonitoring/index';
import { forEach } from 'lodash';
import { message } from 'ant-design-vue';
const playerLength = ref(4)
const span = [24, 12, 8, 6];
const type = [1, 4, 9, 16];
const typeIndex = ref(0);
// 监控视频list
const playerList = ref([
  { url: '', name: '' },
])
// 树形数据
const treeData = ref([
]);
// 树形选中的
const selectedKeys = ref([])
// 默认展开的
const expandedKeys = ref(['0-0']);
// 是否展开父节点
const autoExpandParent = ref(true);
// 搜索
const searchValue = ref('');
// 递归查询
const predicate = (node, val) => node.title === val;
// 查询函数
let arr = []

async function synchronousTree() {
  let res = await serverUrlApi.synchronousTree();
  if (res.code == 0) {
    message.success("同步成功")
    getTree()
  }


}
function queryTree(tree, val) {
  if (!tree || !tree.length) {
    return []
  }
  tree.forEach(element => {
    console.log(element)
    if (element.name.includes(val)) {
      arr.push(element.name)
    }
    if (element.children && element.children.length) {
      queryTree(element.children, val)
    }
  });
}
watch(searchValue, async value => {
  console.log(value)
  expandedKeys.value = []
  arr = []
  // 执行查询
  await queryTree(treeData.value, value);
  if (arr.length) {
    expandedKeys.value = arr
  }
});
// 分屏
function addPlayerList(num) {
  let arr = []
  for (let i = 1; i <= num; i++) {
    arr.push({ url: '', name: '' })
  }
  return arr;

}
function splitScreen(num) {
  typeIndex.value = num
  if (num === 0) {
    playerList.value = addPlayerList(1)
  } else if (num === 1) {
    playerList.value = addPlayerList(4)
  } else if (num === 2) {
    playerList.value = addPlayerList(9)
  } else if (num === 3) {
    playerList.value = addPlayerList(16)
  }
  keyMap.delete('key')
}
// 全屏
const isFullScreen = ref(false);
const toggleFullScreen = () => {
  if (!document.fullscreenElement) {
    // 请求全屏  
    const element = document.querySelector('#videId'); // 替换为你的div的ID  
    if (element.requestFullscreen) {
      element.requestFullscreen().catch(err => {
        console.error('无法进入全屏模式:', err);
      });
      isFullScreen.value = true;
    }
  } else {
    // 退出全屏  
    if (document.exitFullscreen) {
      document.exitFullscreen();
      isFullScreen.value = false;
    }
  }
};
// 轮播
const videoModalRef = ref(null);
function showVideoModal() {
  videoModalRef.value.showDrawer(listData.value);
}

function startInterval(vlist, index, playerListIndex) {


  // if (playerListIndex.value >= playerList.value.length) {
  //   playerListIndex.value = 0
  // }
  // if (index >= vlist.length) {
  //   index = 0
  // }


  playerList.value[playerListIndex].url = vlist[index].url
  playerList.value[playerListIndex].name = vlist[index].title



}
function videoChange(data, secondsConut) {
  var index = 0;
  var playerListIndex = 0;
  var num = playerList.value.length
  var count = 0
  if (data && data.length) {
    // startInterval(data, index, playerListIndex)
    if (data.length <= num) {
      count = data.length
    } else {
      count = num
    }
    playerListIndex = count - 1
    index = count - 1
    for (let i = 0; i < count; i++) {
      playerList.value[i].url = data[i].url
      playerList.value[i].name = data[i].title

    }
    let a = setInterval(() => {
      index++;
      // playerListIndex++;
      if (num == 1) {
        if (index < data.length) {
          startInterval(data, index, playerListIndex)
        } else {
          index = 0
          startInterval(data, index, playerListIndex)
        }
      } else {
        playerListIndex++;
        if (playerListIndex >= num) {
          playerListIndex = 0
        }
        if (index < data.length) {
          startInterval(data, index, playerListIndex)
        } else {
          index = 0
          startInterval(data, index, playerListIndex)
        }
      }


    }, secondsConut ? secondsConut * 1000 : 10000)
  }
}

// 获取树形
const listData = ref([])
async function getTree() {
  let res = await serverUrlApi.querytree();
  sortTree(res.data)
  if (res.data[0].name.includes('根目录')) {
    treeData.value = res.data[0].children;
  } else {
    treeData.value = res.data;
  }
  // return
  listData.value = flattenTree(treeData.value);
}
function sortTree(tree) {
  tree.forEach(element => {
    if (element.online) {
      element['style'] = 'color:#00a65a'
    }
    if (element.children && element.children.length > 0) {
      const trueValues = element.children.filter(item => item.online === true);
      element.name = `${element.name}[${trueValues.length}/${element.children.length}]`
      sortTree(element.children)
    }
  })
}
// 选择通道
const videoIndex = ref(null)
const videoListModalRef = ref(null);
function showVideoListModal(index) {
  videoListModalRef.value.showDrawer();
  videoIndex.value = index
}
function videoSrcChange(record) {



  if (videoIndex.value) {
    playerList.value[videoIndex.value].url = record.url
    playerList.value[videoIndex.value].name = record.title
  }
}
// 选择树形菜单切换监控视频
let keyMap = new Map();
async function treeSelect(key, info) {
  // 判断现在点的监控是否存在
  let indexVlaue = playerList.value.findIndex(item => {
    return item.name === info.node.key
  })
  if (indexVlaue !== -1) {
    return
  }

  // 补缺
  if (keyMap.has('key')) {
    let index = playerList.value.findIndex(item => {
      return !item.url
    })
    if (index !== -1) {
      let res = await serverUrlApi.getUrl({
        ip: info.node.ip,
        Channel: info.node.channel
      })
      if (!res.data.urlStr) {
        message.error('没有视频流');
        return
      }
      playerList.value[index].url = res.data.urlStr
      playerList.value[index].name = info.node.key
      return
    }

    console.log(index);
  }
  // 点击树形父及播放下面的子及
  if (info.node.children && info.node.children.length) {
    for (let i = 0; i < playerList.value.length; i++) {
      let res = await serverUrlApi.getUrl({
        ip: info.node.children[i].ip,
        Channel: info.node.children[i].channel
      })
      playerList.value[i].url = res.data.urlStr
      playerList.value[i].name = info.node.children[i].key
    }
    keyMap.set('key', playerList.value.length - 1)
    return
  }
  // 选中的切换视频
  if (livePlayerIndex.value !== null) {
    let res = await serverUrlApi.getUrl({
      ip: info.node.ip,
      Channel: info.node.channel
    })
    if (!res.data.urlStr) {
      message.error('没有视频流');
      return
    }

    playerList.value[livePlayerIndex.value].url = res.data.urlStr
    playerList.value[livePlayerIndex.value].name = info.node.key
    livePlayerIndex.value++
    if (livePlayerIndex.value >= playerList.value.length) {
      livePlayerIndex.value = 0
    }
    return
  }
  let res = await serverUrlApi.getUrl({
    ip: info.node.ip,
    Channel: info.node.channel
  })
  if (!res.data.urlStr) {
    message.error('没有视频流');
    return
  }
  let url = res.data.urlStr
  let index = keyMap.get('key')
  if (!keyMap.has('key')) {
    keyMap.set('key', 0)
    playerList.value[0].url = url
    playerList.value[0].name = info.node.key
  } else {
    index++;
    if (index >= playerList.value.length) {
      keyMap.set('key', 0)
      playerList.value[0].url = url
      playerList.value[0].name = info.node.key
    } else {
      keyMap.set('key', index)
      playerList.value[index].url = url
      playerList.value[index].name = info.node.key
    }
  }
}

function flattenTree(tree) {
  const result = [];
  addResult(tree, result)
  return result;
}

function addResult(tree, result) {
  tree.forEach(element => {
    if (element.children && element.children.length) {
      addResult(element.children, result)
    } else {
      result.push({ ...element })
    }
  })

}
// 视频窗口聚焦
const livePlayerIndex = ref(null);
function LivePlayerClick(index) {
  livePlayerIndex.value = index

}
onMounted(getTree)
</script>

<style>
.active {
  border: 1px solid red;
}
</style>